package com.moco.launcher.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.StringUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.moco.launcher.LauncherApplication;
import com.moco.launcher.R;
import com.moco.launcher.adapter.DataAdapter;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.link.LinkManager;
import com.moco.launcher.listener.CloudListener;
import com.moco.launcher.listener.VoicePlayListener;
import com.moco.launcher.view.WaveView;
import com.mradar.sdk.record.Logger;
import com.oazon.common.TaskHelper;
import com.oazon.common.TaskHelper.Task;
import com.oazon.common.util.RequestManager;
import com.oazon.common.util.curcity.AddressCallback;
import com.oazon.common.util.curcity.AddressUtil;
import com.oazon.common.util.curcity.ResponseCityBean;
import com.oazon.moco.bean.Metadata;
import com.oazon.moco.link.core.LinkEventController;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.link.ui.SpechEventListener;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.bean.AbstractMedia;
import com.oazon.moco.playlist.db.ServiceMsgDao;
import com.oazon.sonos.bean.Search;
import com.oazon.sonos.bean.SearchResponse;
import com.oazon.sonos.core.SonosControler;
import com.oazon.sonos.listener.SonosListener;
import com.oazon.system.SysActionChannal;
import com.oazon.voicelib.bean.Weather;
import com.oazon.voicelib.model.MusicSemantic;
import com.oazon.voicelib.model.SemanticObj;
import com.oazon.voicelib.model.WeatherSemantic;
import com.oazon.voicelib.service.SpeechServer;

public class VoiceFragment extends BaseFragment {

	private static final String SERVICE_MUSIC = "music";
	private static final String SERVICE_WEATHER = "weather";
	private static final String OPERATION_PLAY = "PLAY";
	private static final String OPERATION_QUERY = "QUERY";

	private static final String TAG = "VoiceFragment";
	private ImageView voiceLightView = null;
	private TextView mVoiceResultView = null;
	private TextView mVoiceHint = null;
	private WaveView mWaveView = null;
	private ImageView mVoiceWait = null;
	private VoicePlayListener mVoicePlayListener = null;
	private ArrayList<Metadata> resultMetadatas = null;
	private String curCity = "";
	private AtomicInteger failureCount = null;
	private AtomicBoolean searchEnd = null;
	private static final int searchProviderCount = 2;
	private ImageView mVoiceResultImageView =null;
	public void registerListener(VoicePlayListener l) {
		mVoicePlayListener = l;
	}

	public VoiceFragment() {
		Log.d(TAG, "voiceFragment======new");
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		LinkSDK.getInstance().registLinkListener(spechEventListener);
		Log.d(TAG, "voiceFragment======oncreat");
		AddressUtil.getCurCityName(activity, new AddressCallback() {

			@Override
			public void onSuccess(String str) {
				try {
					ResponseCityBean bean = JSON.parseObject(str,
							ResponseCityBean.class);
					String cityname = bean.getRetData().getCity();
					if (!"None".equals(cityname)) {
						curCity = cityname;

					} else {
						curCity = bean.getRetData().getProvince();
					}

				} catch (Exception e) {
					onError(e.toString());
				}
			}

			@Override
			public void onError(String er) {
			}
		});
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	SpechEventListener spechEventListener = new SpechEventListener(
			LinkEventController.uiSource) {

		@Override
		protected void speechVolume(int volume) {
			if (volume > 0) {
				mWaveView.setAmplitude(volume * 3, true);
			} else {
				mWaveView.setAmplitude(volume, false);
			}
		}

		@Override
		protected void speechEnd() {
			hideVoiceUi();
			startVoiceWait();
			mVoiceResultView.setVisibility(View.VISIBLE);
			mVoiceResultView.setText("正在识别...");
		}

		@Override
		protected void speechUndertandError(final String strError) {

			stopVoiceWait();
			mVoiceResultView.setText(strError);
			mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
			mHandler.sendEmptyMessageDelayed(RESTART, 2000);
		}

		@Override
		protected void speechSpeakComplite(boolean iswake) {
			if (!iswake) {
				mHandler.sendEmptyMessage(RESTART);
			}
		}

		@Override
		protected void speechResultObject(SemanticObj semanticObj) {
			hideVoiceUi();
			mVoiceResultView.setVisibility(View.VISIBLE);
			String service = semanticObj.getService();
			if (service == null) {
				mVoiceResultView.setText(semanticObj.getText());
				Logger.i(TAG, "semanticObj.getText()=="+semanticObj.getText());
			} else {

				if (SERVICE_MUSIC.equals(service)
						&& OPERATION_PLAY.equals(semanticObj.getOperation())) {
					final String artist = ((MusicSemantic) semanticObj.getSemantic())
							.getSlots().getArtist();
					final String title = ((MusicSemantic) semanticObj.getSemantic())
							.getSlots().getSong();
					final String album = ((MusicSemantic) semanticObj.getSemantic())
							.getSlots().getAlbum();

					String play_item = LinkSDK.getAppContext().getResources()
							.getString(R.string.will_play);
					//play_item += title;
					play_item += "...";
					mVoiceResultView.setText(play_item);
					//解决正在搜索歌曲“xx”，语音没有播放完整就跳转到“即将播放xx歌曲”
					MediaPlayer mp_search = MediaPlayer.create(
							getContext(), R.raw.searchsong);
					mp_search
							.setOnCompletionListener(new OnCompletionListener() {

								@Override
								public void onCompletion(
										MediaPlayer mp_search) {
									// TODO Auto-generated method stub
									queryMusic(artist, title, album);
									mp_search.release();
								}
							});
					mp_search.start();
					
				} else if (SERVICE_WEATHER.equals(service)
						&& OPERATION_QUERY.equals(semanticObj.getOperation())) {
					String cityname = "";
					cityname = ((WeatherSemantic) semanticObj.getSemantic())
							.getSlots().getLocation().getCityAddr();
					String date = ((WeatherSemantic) semanticObj.getSemantic())
							.getSlots().getDatetime().getDate();
					queryWeather(cityname, date);

				}else{
					mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
					mVoiceResultView.setText("我不理解");
					mHandler.sendEmptyMessageDelayed(RESTART,2000);
				}
			}
		}
	};

	private int paseDate(String date) {
		if ("CURRENT_DAY".equals(date)) {
			return 0;
		}
		int future = 0;
		Calendar cal = Calendar.getInstance();
		int curYear = cal.get(Calendar.YEAR);// 获取年份
		int curMonth = cal.get(Calendar.MONTH) + 1;// 获取月份
		int curDay = cal.get(Calendar.DATE);// 获取日

		String[] dates = date.split("[-]");
		int year = Integer.parseInt(dates[0]);
		int month = Integer.parseInt(dates[1]);
		int day = Integer.parseInt(dates[2]);

		// 得到当前月份的最大天数
		Calendar calendar = Calendar.getInstance();
		calendar.set(curYear, cal.get(Calendar.MONTH), 1);
		calendar.roll(Calendar.DATE, false);
		int curMonthMaxDay = calendar.get(Calendar.DATE);

		// 年月日的相差
		int minusYear = year - curYear;
		int minusMonth = month - curMonth;
		int minusDay = day - curDay;

		if (minusYear > 0) {
			minusMonth += 12 * minusYear;
		}

		if (minusMonth > 0) {
			minusDay += curMonthMaxDay * minusMonth;
		}

		if (minusDay >= 6) {
			return -1;
		} else {
			future = minusDay;
		}
		return future;
	}

	private String formateDate(String date) {
		String params[] = date.split("[-]");
		if (params[1].length() == 1) {
			params[1] = "0" + params[1];
		}
		date = params[0] + params[1] + params[2];
		return "day_" + date;
	}

	private void queryWeather(String cityname, final String date) {

		if ("CURRENT_CITY".equals(cityname)) {
			try {
				cityname = curCity;
			} catch (Exception e) {

			}
		}

		String weatherUrl = "http://v.juhe.cn/weather/index?dtype=json&key=35ca3c327c75ed9fbc2ca4a944c81aad&";
		String queryCityname = "";
		try {
			// 汉字转码，不然找不到该城市
			queryCityname = URLEncoder.encode(cityname, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}// end try catch

		weatherUrl = weatherUrl + "cityname=" + queryCityname;
		mVoiceResultView.setText("正在查询天气...");
		Log.d(TAG, "weatherUrl = " + weatherUrl);

		final String showCityName = cityname;

		RequestManager.sendRequest(this.getActivity(), weatherUrl,
				new CloudListener() {

					@Override
					public void onResponse(String response) {

						try {
							stopVoiceWait();
							
							Log.d(TAG, response);
							Weather weather = JSON.parseObject(response,
									Weather.class);
							int futrue = paseDate(date);
							if (futrue > 0) {
								final String futrueDate = formateDate(date);

								showWeather(showCityName, weather.getResult()
										.getFuture().get(futrueDate)
										.getWeather(), weather.getResult()
										.getFuture().get(futrueDate)
										.getTemperature());

							} else if (futrue == 0) {
								showWeather(showCityName, weather.getResult()
										.getToday().getWeather(), weather
										.getResult().getSk().getTemp());
							} else {
								String warn = "只能查询未来5天内的天气";
								mVoiceResultView.setText(warn);
								mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
								LinkManager.getInstance().startSpeak(warn);
							}
						} catch (Exception e) {
							mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
							mVoiceResultView.setText("没有查到该城市");
							mHandler.sendEmptyMessageDelayed(RESTART,1000);
						}

					}

					@Override
					public void onError(int err, String msg) {
						mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
						mVoiceResultView.setText("没有查到该城市");
						mHandler.sendEmptyMessageDelayed(RESTART,1000);
					}
				});
	}

	private void showWeather(String showCityName, String weather, String temp) {
		try {
			String strWeather = "" + showCityName + " : " + weather + "\r\n"
					+ "温度：" + temp;
			mVoiceResultImageView.setImageResource(R.drawable.voicerusult_true);
			mVoiceResultView.setText(strWeather);
			LinkManager.getInstance().startSpeak(strWeather);

		} catch (Exception e) {
			mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
			mVoiceResultView.setText("没有查到该城市");
			mHandler.sendEmptyMessageDelayed(RESTART,2000);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.voice_layout, container,
				false);
		mVoiceResultView = (TextView) rootView.findViewById(R.id.voice_result);
		voiceLightView = (ImageView) rootView.findViewById(R.id.voice_light);
		mVoiceResultImageView = (ImageView) rootView.findViewById(R.id.voice_result_pic);
		voiceLightView.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return false;
			}
		});
		voiceLightView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				
				mHandler.sendEmptyMessage(RESTART);
				LinkManager.getInstance().stopSppech();
			
			}
		});
		rootView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				mHandler.sendEmptyMessage(RESTART);
				LinkManager.getInstance().stopSppech();
			}
		});
		mWaveView = (WaveView) rootView.findViewById(R.id.wave_view);

		mVoiceWait = (ImageView) rootView.findViewById(R.id.voice_wait);
		mVoiceHint = (TextView) rootView.findViewById(R.id.voice_hint);
//		mVoiceHint.setTextColor(0xffee7b1d);
		actionStart();
		return rootView;
	}

	private void actionStart() {
		mWaveView.start();
	}

	private void actionStop() {
		mWaveView.stop();
		stopAlbumAnimation(mVoiceWait);
	}

	private void hideVoiceUi() {
		mWaveView.setVisibility(View.GONE);
		mVoiceHint.setVisibility(View.GONE);
		voiceLightView.setVisibility(View.GONE);
	}
	private static final int RESTART = 1;
	private static final int PLAY = 2;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case RESTART:
				mVoicePlayListener.onMusicListSelected(null);
				break;
			case PLAY:
				if (mVoicePlayListener != null) {
					mVoicePlayListener.onMusicListSelected(resultMetadatas);
				}
				break;
			}
		}
	};

	private void queryMusic(String artist, String song, String album) {
		String term = "";
		try {
			if (StringUtils.isNotBlank(artist)) {
				//param = "artist=";
				//term += URLEncoder.encode(artist, "utf8");
				term += artist;
			}
			term += "|";
			if (StringUtils.isNotBlank(album)) {
				//param += "albumenTitle=";
				//term += URLEncoder.encode(album, "utf8");
				term  += album;
			}
			term += "|";
			if (StringUtils.isNotBlank(song)) {
				//param += "term=";
				//term += URLEncoder.encode(song, "utf8");
				term += song;
			}
			//term += "&";

		} catch (Exception e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RESTART);
		}
		//String strUrl = MOCO_CONSTANTS.SERACH_URL + term;

		//Log.d(TAG, "strUrl======== " + strUrl);
		startVoiceWait();
		
		SearchListener o2SearchListener = new SearchListener();
		o2SearchListener.searchProvider = "o2";
		Search param = new Search();
		param.setId("search:tracks");
		param.setIndex(0);
		param.setCount(2);
		param.setTerm(term);
		param.setProvider("o2");
		SonosControler.getInstance(this.getContext(), null).search(this.getContext(), param, o2SearchListener);

		SearchListener wangyiSearchListener = new SearchListener();
		wangyiSearchListener.searchProvider = MOCO_CONSTANTS.PROVIDER_WANNGYI;
		param.setProvider(MOCO_CONSTANTS.PROVIDER_WANNGYI);
		SonosControler.getInstance(this.getContext(), ServiceMsgDao.getInstance(getContext()).getServiceMsgByProvider(MOCO_CONSTANTS.PROVIDER_WANNGYI)).search(this.getContext(), param, wangyiSearchListener);
	}

	public class SearchListener implements SonosListener{
		public String searchProvider = null;
		@Override
		public void onResponse(Object response) {
			synchronized (VoiceFragment.this) {
				Log.d(TAG, searchProvider + "response= " + response);
				stopVoiceWait();
				if(response == null){
					if(failureCount.incrementAndGet()==searchProviderCount){
						mVoiceResultView.setText("没有找到这首歌");
						mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
						mHandler.sendEmptyMessageDelayed(RESTART,2000);
					}
					return;
				}
				try {
				
					if(((SearchResponse)response).getSearchResult() == null) {
						if(failureCount.incrementAndGet()==searchProviderCount){
							mVoiceResultView.setText("没有找到这首歌");
							mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
							mHandler.sendEmptyMessageDelayed(RESTART,2000);
						}
						return;
					}
					
					List<AbstractMedia> items = ((SearchResponse)response).getSearchResult().getMediaCollectionOrMediaMetadata();
			
					if (items.size() > 0 && searchEnd.get()==false) {
						resultMetadatas = (ArrayList<Metadata>) DataAdapter
								.paseMetadatas(items, null, searchProvider);
					}
					Log.d(TAG, searchProvider + "resultMetadatas= " + resultMetadatas);
					if (resultMetadatas == null || resultMetadatas.size() <= 0) {
						if(failureCount.incrementAndGet()==searchProviderCount){
							mVoiceResultView.setText("没有找到这首歌");
							mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
							mHandler.sendEmptyMessageDelayed(RESTART,2000);
							Log.d("WGZ", "mHandler.sendEmptyMessageDelayed(RESTART,1000);");
						}
					} else {
						if(searchEnd.get()==false){
							if(resultMetadatas.get(0).getTitle()!=null){
								mVoiceResultView.setText("即将播放"+"\""+resultMetadatas.get(0).getTitle()+"\"");
							}else{
								mVoiceResultView.setText("即将播放");
							}
							mVoiceResultImageView.setImageResource(R.drawable.voicerusult_true);
							mHandler.sendEmptyMessageDelayed(PLAY, 2000);
							Log.d(TAG, searchProvider+"的歌曲:mHandler.sendEmptyMessageDelayed(PLAY, 1000);");
							searchEnd.set(true);
						}
					}
				} catch (Exception e) {
					//stopVoiceWait();
					if(failureCount.incrementAndGet()==searchProviderCount){
						mVoiceResultView.setText("没有找到这首歌");
						mHandler.sendEmptyMessageDelayed(RESTART,2000);
						Log.d(TAG, searchProvider + "没有找到这首歌" );
					}
				}finally{
					if(searchEnd.get() == true || failureCount.get()==searchProviderCount){
//						stopVoiceWait();
					}
				}
			}
		}
		
		@Override
		public void onError(int err, String msg) {

			Log.d(TAG, searchProvider + "err= " + msg);
			synchronized (VoiceFragment.this) {
				if(failureCount.incrementAndGet()==searchProviderCount){
					mHandler.sendEmptyMessage(RESTART);
					stopVoiceWait();
					mVoiceResultImageView.setImageResource(R.drawable.voicerusult_false);
					mVoiceResultView.setText(R.string.check_network);
				}
			}
		}
	};
	
	private void startVoiceWait() {
		failureCount = new AtomicInteger(0);
		searchEnd = new AtomicBoolean(false);
		mVoiceWait.setVisibility(View.VISIBLE);
		startAlbumAnimation(mVoiceWait);
	}

	private void stopVoiceWait() {
		stopAlbumAnimation(mVoiceWait);
		mVoiceWait.setVisibility(View.GONE);
	}

	public void startAlbumAnimation(View view) {
		RotateAnimation rotateAnimation = new RotateAnimation(0, 359,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		rotateAnimation.setDuration(3000);
		rotateAnimation.setInterpolator(new LinearInterpolator());
		rotateAnimation.setRepeatCount(-1);
		rotateAnimation.setRepeatMode(Animation.RESTART);
		rotateAnimation.setFillAfter(true);
		rotateAnimation.setFillEnabled(true);

		if (view != null) {
			view.startAnimation(rotateAnimation);
		}
	}

	public void stopAlbumAnimation(View view) {
		if (view != null) {
			view.clearAnimation();
		}
	}
	
	@Override
	public void onResume() {
		SysActionChannal.getInstance().setPauseAllTimer(true);
		super.onResume();
	}
	@Override
	public void onPause() {
		SysActionChannal.getInstance().setPauseAllTimer(false);
		actionStop();
		super.onPause();
	}
	
	@Override
	public void onStop() {
		super.onStop();
	}
	@Override
	public void onDestroy() {
		LinkSDK.getInstance().unregistLinkListener(spechEventListener);
		super.onDestroy();
	}
}
